/**
 * useDocument钩子 - 管理文档生成、修改和导出的状态与逻辑
 * 
 * 该钩子提供了文档生成的完整流程控制，包括：
 * - 从后端API流式接收文档生成过程
 * - 缓存和检索已生成的文档
 * - 处理文档修改请求
 * - 支持文档导出和复制功能
 * - 管理API密钥对话框
 */
import { useState, useEffect, useCallback } from "react";
import {
  cacheDiagramAndExplanation,
  getCachedDiagram,
  getCachedExplanation,
  cacheDocument,
  getCachedDocument,
} from "~/app/_actions/cache";
import { getLastGeneratedDate } from "~/app/_actions/repo";
import { getCostOfGeneration } from "~/lib/fetch-backend";
import { exampleRepos } from "~/lib/exampleRepos";
import { robustJsonParse, safeJsonParse, testJsonParsing } from "~/lib/json-utils";

// 全局变量声明，让TypeScript不报错
declare global {
  interface Window {
    _isDocumentMode?: boolean;
    _isDiagramMode?: boolean;
  }
}

// 在客户端环境中，确保我们是在document页面且不使用useDiagram
if (typeof window !== 'undefined') {
  // 文档页面初始化时的简化日志
  // console.log("========================================");
  // console.log("【DOCUMENT HOOK 初始化】");
  const pathname = window.location.pathname;
  
  // 检查路径是否包含document，并标记为文档模式
  if (pathname.includes('/document')) {
    window._isDocumentMode = true;
    
    // 如果存在图表模式标记，则删除
    if (window._isDiagramMode) {
      // console.warn("检测到图表模式标记，这可能导致冲突，正在删除");
      delete window._isDiagramMode;
    }
  }
  
  // console.log("========================================");
}

/**
 * 文档生成流状态接口
 * 跟踪文档生成的各个阶段，从开始到完成的整个过程
 */
export interface DocumentStreamState {
  status:
    | "idle"
    | "started"
    | "explanation_sent"
    | "explanation"
    | "explanation_chunk"
    | "mapping_sent"
    | "mapping"
    | "mapping_chunk"
    | "document_sent"
    | "document"
    | "document_chunk"
    | "complete"
    | "error";
  message?: string;     // 当前状态的消息说明
  explanation?: string; // 仓库架构分析文本
  mapping?: string;     // 组件到文件路径的映射
  document?: string;    // 生成的文档内容
  error?: string;       // 错误信息
}

/**
 * 文档流响应接口，定义从服务器接收的SSE消息结构
 */
interface DocumentStreamResponse {
  status: DocumentStreamState["status"];
  message?: string;  // 状态消息
  chunk?: string;    // 流式接收的内容块
  explanation?: string;  // 完整的解释
  mapping?: string;      // 完整的映射
  document?: string;     // 完整的文档
  error?: string;        // 错误信息
  valid?: boolean;       // 有效性标志
}

/**
 * 文档管理钩子，负责处理项目文档的生成、修改、导出和交互
 * 
 * @param username - GitHub用户名
 * @param repo - GitHub仓库名
 * @returns 包含文档状态、操作函数和辅助功能的钩子对象
 */
export function useDocument(username: string, repo: string) {
  // 安全检查：确保当前不是在图表模式
  if (typeof window !== 'undefined' && window._isDiagramMode) {
    // console.error("【严重错误】检测到使用图表模式标记，但正在使用useDocument钩子！");
    // 移除错误的标记
    delete window._isDiagramMode;
    // 设置正确的标记
    window._isDocumentMode = true;
  }
  
  const [document, setDocument] = useState<string>("");
  const [error, setError] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(true);
  const [lastGenerated, setLastGenerated] = useState<Date | undefined>();
  const [cost, setCost] = useState<string>("");
  const [showApiKeyDialog, setShowApiKeyDialog] = useState(false);
  const [state, setState] = useState<DocumentStreamState>({ status: "idle" });
  const [hasUsedFreeGeneration, setHasUsedFreeGeneration] = useState<boolean>(
    () => {
      if (typeof window === "undefined") return false;
      return localStorage.getItem("has_used_free_generation") === "true";
    },
  );
  const [currentDocumentType, setCurrentDocumentType] = useState<string>(() => {
    if (typeof window === "undefined") return "overview-doc";
    return localStorage.getItem("current_document_type") || "overview-doc";
  });
  const [selectedModel, setSelectedModel] = useState<string>(() => {
    if (typeof window === "undefined") return "openai-o3";
    return localStorage.getItem("selected_model") || "openai-o3";
  });

  useEffect(() => {
    const storedModel = localStorage.getItem("selected_model");
    if (storedModel) {
      setSelectedModel(storedModel);
    }
  }, []);

  // 默认文档类型常量
  const DEFAULT_DOC_TYPE = "overview-doc";

  /**
   * 生成文档的函数
   * @param instructions - 用户自定义指令
   * @param githubPat - GitHub个人访问令牌
   * @param documentType - 文档类型
   */
  const generateDocument = useCallback(
    async (
      instructions = "",
      githubPat?: string,
      documentType?: string
    ) => {
      try {
        // 使用传入的文档类型，或者当前状态中的类型，或者默认值
        const actualDocType = documentType || currentDocumentType || DEFAULT_DOC_TYPE;
        
        // console.log(`【文档生成-开始】文档类型: '${actualDocType}'`);
        
        // 添加更详细的日志，检查文档类型是否有效
        const validDocTypesSet = new Set(["overview-doc", "detailed-doc", "database-doc", "api-doc", "deployment-doc"]);
        const isValidDocType = validDocTypesSet.has(actualDocType);
        
        // 只在真正无效的情况下使用默认值
        let effectiveDocType = actualDocType;
        if (!effectiveDocType || effectiveDocType === "diagram" || !validDocTypesSet.has(effectiveDocType)) {
          // console.warn(`【警告】检测到无效的文档类型: "${effectiveDocType}"，将使用默认值`);
          effectiveDocType = DEFAULT_DOC_TYPE;
        }

        // console.log(`【文档生成】使用文档类型: ${effectiveDocType}`);
        setState({ status: "started" });
        setLoading(true);

        // 设置currentDocumentType
        // console.log(`【文档类型更新】从 ${currentDocumentType} 变为 ${effectiveDocType}`);
        setCurrentDocumentType(effectiveDocType);

        // 选择API端点
        let endpoint;
        
        // 记录模型选择和API端点
        const selectedModel = localStorage.getItem("selected_model") || "openai-o3";
        const baseUrl = process.env.NEXT_PUBLIC_API_DEV_URL ?? "https://api.codemariner.com";
        
        if (selectedModel === "deepseek") {
          endpoint = `${baseUrl}/deepseek/doc/stream`;
        } else {
          endpoint = `${baseUrl}/openai/doc/stream`;
        }
        
        // 构建请求体 - 确保包含有效的文档类型
        const requestBody = {
          username,
          repo,
          instructions,
          api_key: localStorage.getItem("api_key") ?? undefined,
          github_pat: githubPat,
          model: selectedModel,
          document_type: effectiveDocType
        };
        
        const response = await fetch(endpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(requestBody),
        });
        
        if (!response.ok) {
          throw new Error("Failed to start streaming");
        }
        
        const reader = response.body?.getReader();
        if (!reader) {
          throw new Error("No reader available");
        }

        let explanation = "";
        let mapping = "";
        let documentText = "";

        // 处理流
        const processStream = async () => {
          try {
            while (true) {
              const { done, value } = await reader.read();
              if (done) {
                // console.log(`【DEBUG-HOOK】[文档生成] 流读取完成，目前收集到的文档类型: ${currentDocumentType}`);
                // console.log(`【BUG排查-HOOK-9】流读取完成，收集到的文档长度: ${documentText.length} 字符`);
                break;
              }

              // 将块转换为文本
              const chunk = new TextDecoder().decode(value);
              const lines = chunk.split("\n");

              // 处理每个SSE消息
              for (const line of lines) {
                if (line.startsWith("data: ")) {
                  try {
                    // 记录原始JSON字符串
                    const jsonStr = line.slice(6).trim();
                    if (!jsonStr) continue;
                    
                    // console.log("原始JSON字符串:", jsonStr.substring(0, 100) + (jsonStr.length > 100 ? "..." : ""));
                    
                    // 使用健壮的JSON解析
                    const data = robustJsonParse(jsonStr, "文档-") as DocumentStreamResponse;
                    
                    // 如果解析成功，处理数据...
                    if (!data) {
                      // console.error("无法解析JSON数据");
                      continue;
                    }
                    
                    // 如果收到错误，立即停止加载
                    if (data.error) {
                      setState({ status: "error", error: data.error });
                      setLoading(false);
                      return;
                    }

                    // 根据消息类型更新状态
                    switch (data.status) {
                      case "started":
                        setState((prev) => ({
                          ...prev,
                          status: "started",
                          message: data.message,
                        }));
                        break;
                      case "explanation_sent":
                        setState((prev) => ({
                          ...prev,
                          status: "explanation_sent",
                          message: data.message,
                        }));
                        break;
                      case "explanation":
                        setState((prev) => ({
                          ...prev,
                          status: "explanation",
                          message: data.message,
                        }));
                        break;
                      case "explanation_chunk":
                        if (data.chunk) {
                          explanation += data.chunk;
                          setState((prev) => ({ ...prev, explanation }));
                        }
                        break;
                      case "mapping_sent":
                        setState((prev) => ({
                          ...prev,
                          status: "mapping_sent",
                          message: data.message,
                        }));
                        break;
                      case "mapping":
                        setState((prev) => ({
                          ...prev,
                          status: "mapping",
                          message: data.message,
                        }));
                        break;
                      case "mapping_chunk":
                        if (data.chunk) {
                          mapping += data.chunk;
                          setState((prev) => ({ ...prev, mapping }));
                        }
                        break;
                      case "document_sent":
                        setState((prev) => ({
                          ...prev,
                          status: "document_sent",
                          message: data.message,
                        }));
                        break;
                      case "document":
                        setState((prev) => ({
                          ...prev,
                          status: "document",
                          message: data.message,
                        }));
                        break;
                      case "document_chunk":
                        if (data.chunk) {
                          // 内联验证数据块
                          const chunk = data.chunk;
                          if (chunk && chunk.trim() !== "" && 
                              !/\[ERROR\]/i.test(chunk) && 
                              !/\bNaN\b/.test(chunk) &&
                              !/\bundefined\b/.test(chunk) &&
                              !/\bnull\b/.test(chunk) &&
                              !/error occurred/i.test(chunk) &&
                              !/failed to/i.test(chunk)) {
                            documentText += chunk;
                            setState((prev) => ({ ...prev, document: documentText }));
                          } else {
                            // console.warn("收到无效的Markdown块，已跳过");
                          }
                        }
                        break;
                      case "complete":
                        // 内联验证最终文档
                        const finalDoc = data.document || "";
                        const isDocValid = finalDoc && 
                                           finalDoc.trim() !== "" && 
                                           finalDoc.includes('#') && 
                                           /^#+ .+$/m.test(finalDoc) && 
                                           finalDoc.split('\n').length > 10;
                        
                        if (isDocValid) {
                          setState({
                            status: "complete",
                            explanation: data.explanation || "",
                            document: finalDoc,
                          });
                          // console.log(`【DEBUG-HOOK】[文档完成] 文档有效，将文档状态设置为完成`);
                        } else {
                          // console.error("收到的最终文档无效或为空");
                          // 尝试使用之前收集的块作为备份
                          if (documentText && documentText.trim() !== "") {
                            // console.log("使用累积的文档块作为备份");
                            setState({
                              status: "complete",
                              explanation: data.explanation || "",
                              document: documentText,
                            });
                          } else {
                            setState({ 
                              status: "error", 
                              error: "文档生成失败或内容无效。请尝试重新生成。" 
                            });
                          }
                        }
                        const date = await getLastGeneratedDate(username, repo);
                        setLastGenerated(date ?? undefined);
                        if (!hasUsedFreeGeneration) {
                          localStorage.setItem(
                            "has_used_free_generation",
                            "true",
                          );
                          setHasUsedFreeGeneration(true);
                        }
                        // 正确处理流式处理结束
                        // console.log(`【DEBUG-HOOK】[文档完成] 文档生成完成，类型: ${effectiveDocType}，当前类型: ${currentDocumentType}`);
                        try {
                          setDocument(finalDoc);
                          // console.log(`【DEBUG-HOOK】[文档缓存] 准备缓存文档，类型: ${effectiveDocType}，长度: ${finalDoc.length}，使用API密钥: ${!!localStorage.getItem("api_key")}`);
                          await cacheDocument(
                            username,
                            repo,
                            finalDoc,
                            !!localStorage.getItem("api_key"),
                            effectiveDocType // 添加documentType参数
                          );
                          // console.log(`【DEBUG-HOOK】[文档缓存] 文档已缓存，类型: ${effectiveDocType}`);
                          await getCostOfGeneration(username, repo)
                            .then((cost) => {
                              if (cost) {
                                // console.log(`【DEBUG-HOOK】[文档成本] 获取到生成成本: ${cost}`);
                                setCost(cost);
                              }
                            })
                            .catch((err) => {
                              // console.error(`【DEBUG-HOOK】[文档成本] 获取生成成本时出错:`, err);
                            });
                          setLoading(false);
                        } catch (error) {
                          // console.error(`【DEBUG-HOOK】[文档缓存] 缓存文档时出错:`, error);
                        }
                        break;
                      case "error":
                        setState({ status: "error", error: data.error });
                        break;
                    }
                  } catch (e) {
                    // console.error("Error parsing SSE message:", e);
                    
                    // 尝试使用测试工具诊断JSON解析问题
                    try {
                      const jsonStr = line.slice(6).trim();
                      const testResult = testJsonParsing(jsonStr);
                      
                      if (testResult.success && testResult.result) {
                        // console.log(`使用${testResult.method}方法成功解析JSON`);
                        const data = testResult.result as DocumentStreamResponse;
                        
                        // 这里可以添加数据处理逻辑，与try块中相同
                        if (data.status === "complete") {
                          const safeDocument = data.document || "";
                          setState({
                            status: "complete",
                            explanation: data.explanation || "",
                            document: safeDocument,
                          });
                        }
                      } else {
                        // console.error("所有JSON解析尝试都失败了");
                      }
                    } catch (recoveryError) {
                      // console.error("尝试恢复JSON解析失败:", recoveryError);
                    }
                  }
                }
              }
            }
          } finally {
            reader.releaseLock();
          }
        };

        await processStream();
      } catch (error) {
        setState({
          status: "error",
          error:
            error instanceof Error
              ? error.message
              : "An unknown error occurred",
        });
        setLoading(false);
      }
    },
    [username, repo, hasUsedFreeGeneration, selectedModel, currentDocumentType],
  );

  // 当文档生成完成时，缓存文档
  useEffect(() => {
    if (state.status === "complete" && state.document) {
      // 缓存生成的文档
      const hasApiKey = !!localStorage.getItem("api_key");
      // console.log(`[useEffect] 文档完成，准备缓存，类型: ${currentDocumentType}, 长度: ${state.document.length}`);
      void cacheDocument(
        username,
        repo,
        state.document,
        hasApiKey,
        currentDocumentType
      );
      setDocument(state.document);
      void getLastGeneratedDate(username, repo).then((date) =>
        setLastGenerated(date ?? undefined),
      );
    } else if (state.status === "error") {
      // console.log(`[useEffect] 状态错误: ${state.error || '未知错误'}`);
      setLoading(false);
    }
  }, [state.status, state.document, username, repo, currentDocumentType]);

  // 获取文档的函数
  const getDocument = useCallback(async () => {
    setLoading(true);
    setError("");
    setCost("");

    try {
      // 首先检查缓存 - 修复：传递当前文档类型
      // console.log(`[getDocument] 尝试获取缓存文档，类型: ${currentDocumentType}`);
      const cached = await getCachedDocument(username, repo, currentDocumentType);
      const githubPat = localStorage.getItem("github_pat");

      if (cached) {
        // console.log(`[getDocument] 找到缓存文档，类型: ${currentDocumentType}, 长度: ${cached.length}`);
        setDocument(cached);
        const date = await getLastGeneratedDate(username, repo);
        setLastGenerated(date ?? undefined);
        return;
      }
      
      // console.log(`[getDocument] 未找到缓存文档，将生成新文档，类型: ${currentDocumentType}`);

      // 获取成本估计
      const costEstimate = await getCostOfGeneration(username, repo);

      if (!costEstimate) {
        // console.error("Cost estimation failed");
        setError("Failed to estimate cost. Please try again.");
        return;
      }

      setCost(costEstimate);

      // 开始流式生成文档
      await generateDocument("", githubPat ?? undefined, currentDocumentType);

    } catch (error) {
      // console.error("Error in getDocument:", error);
      setError("Something went wrong. Please try again later.");
    } finally {
      setLoading(false);
    }
  }, [username, repo, generateDocument, currentDocumentType]);

  // 初始加载时获取文档
  useEffect(() => {
    void getDocument();
  }, [getDocument]);

  /**
   * 检查给定的仓库名称是否为示例仓库
   * @param repoName - 仓库名称
   * @returns 如果是示例仓库则返回 true，否则返回 false
   */
  const isExampleRepo = (repoName: string) => {
    return Object.values(exampleRepos).some(path => 
      path.toLowerCase().includes(repoName.toLowerCase())
    );
  };

  /**
   * 处理文档修改请求
   * 
   * 将用户的修改指令发送到后端API，根据所选模型选择合适的端点。
   * 处理整个修改过程的状态变化，包括加载状态和错误处理。
   * 
   * @param instructions - 用户提供的修改指令，描述如何更改文档
   * @returns Promise<void>
   */
  const handleModify = async (instructions: string) => {
    if (isExampleRepo(repo)) {
      setError("Example repositories cannot be modified.");
      return;
    }

    setLoading(true);
    setError("");
    setCost("");
    
    try {
      // 从 localStorage 获取当前模型
      const currentModel = localStorage.getItem("selected_model") || "openai-o3";
      // console.log("Current model for document modification:", currentModel);
      
      // 根据当前模型选择端点
      const baseUrl = process.env.NEXT_PUBLIC_API_DEV_URL ?? "https://api.codemariner.com";
      let endpoint = `${baseUrl}/openai/doc/modify`;
      
      if (currentModel === "deepseek") {
        // console.log("Using DeepSeek document modify endpoint");
        endpoint = `${baseUrl}/deepseek/doc/modify`;
      } else {
        // console.log("Using OpenAI document modify endpoint");
      }
      
      // console.log("Document modify endpoint:", endpoint);
      
      // 获取当前的文档和解释 - 修复：传递文档类型
      // console.log(`[修改文档] 尝试获取当前文档，类型: ${currentDocumentType}`);
      const currentDocument = await getCachedDocument(username, repo, currentDocumentType);
      const explanation = await getCachedExplanation(username, repo);
      
      // console.log("Document modify check - currentDocument exists:", !!currentDocument);
      // console.log("Document modify check - explanation exists:", !!explanation);
      // console.log("Document modify check - currentDocument length:", currentDocument?.length || 0);
      // console.log("Document modify check - explanation length:", explanation?.length || 0);
      // console.log("Document modify check - documentType:", currentDocumentType);
      
      if (!currentDocument && !explanation) {
        throw new Error("No existing document or explanation found to modify");
      }
      
      // 准备请求体
      const requestBody = {
        instructions,
        current_document: currentDocument ?? "",  // 确保是字符串
        explanation: explanation ?? "",  // 确保是字符串
        api_key: localStorage.getItem("api_key") ?? undefined,
        document_type: currentDocumentType, // 添加文档类型参数
      };
      
      // console.log("Document modification request (excluding API key):", {
      //   ...requestBody,
      //   api_key: requestBody.api_key ? "[REDACTED]" : undefined,
      //   instructions_length: instructions.length,
      //   current_document_sample: (currentDocument || "").substring(0, 100) + "...",
      //   explanation_sample: (explanation || "").substring(0, 100) + "...",
      //   document_type: currentDocumentType
      // });
      
      // 发送请求
      // console.log("发送文档修改请求...");
      const response = await fetch(endpoint, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestBody),
      });
      
      // console.log("文档修改响应状态码:", response.status);
      
      // 处理响应
      if (response.status === 429) {
        throw new Error("Rate limit exceeded. Please try again later.");
      }
      
      if (!response.ok) {
        // console.error("文档修改请求失败:", response.status, response.statusText);
        const errorText = await response.text();
        // console.error("错误响应内容:", errorText);
        throw new Error(`Request failed with status ${response.status}: ${errorText || response.statusText}`);
      }
      
      const data = await response.json();
      // console.log("文档修改响应数据类型:", typeof data);
      // console.log("文档修改响应数据结构:", Object.keys(data));
      
      if (data.error) {
        // console.error("服务器返回错误:", data.error);
        throw new Error(data.error);
      }
      
      if (!data.document) {
        // console.error("响应中没有document字段:", data);
        throw new Error("Invalid response format: missing document field");
      }
      
      // console.log("文档修改成功，新文档长度:", data.document.length);
      
      // 更新文档
      setDocument(data.document);
      await cacheDocument(
        username,
        repo,
        data.document,
        !!localStorage.getItem("api_key"),
        currentDocumentType
      );
    } catch (error) {
      // console.error("Error modifying document:", error);
      setError(error instanceof Error ? error.message : "Failed to modify document. Please try again later.");
    } finally {
      setLoading(false);
    }
  };

  /**
   * 重新生成文档的函数
   * @param instructions - 用户提供的自定义指令
   * @param documentType - 文档类型
   */
  const handleRegenerate = async (instructions: string, documentType?: string) => {
    // console.log(`【BUG排查-REGEN-1】handleRegenerate接收到的documentType: ${documentType || "未定义"}`);
    
    // 确保我们有一个有效的文档类型
    const validDocTypesSet = new Set(["overview-doc", "detailed-doc", "database-doc", "api-doc", "deployment-doc"]);
    
    // 使用传入的文档类型，如果没有则使用当前文档类型，如果都没有则使用默认类型
    let docType = documentType || currentDocumentType || DEFAULT_DOC_TYPE;
    
    // 验证文档类型的有效性
    if (!validDocTypesSet.has(docType)) {
      // console.warn(`【BUG排查-REGEN-2】警告: 检测到无效的文档类型: "${docType}"`);
      docType = DEFAULT_DOC_TYPE;
      // console.log(`【BUG排查-REGEN-3】将使用默认文档类型: "${DEFAULT_DOC_TYPE}" 替代`);
    } else {
      // console.log(`【BUG排查-REGEN-4】将使用有效的文档类型: "${docType}"`);
    }
    
    // 如果传入了文档类型且与当前类型不同，需要更新状态和localStorage
    if (documentType && documentType !== currentDocumentType && validDocTypesSet.has(documentType)) {
      // console.log(`【文档类型更新】从 ${currentDocumentType} 更新为 ${documentType}`);
      
      // 更新钩子状态
      setCurrentDocumentType(documentType);
      
      // 同步到localStorage
      if (typeof window !== 'undefined') {
        localStorage.setItem('current_document_type', documentType);
        // console.log(`【localStorage更新】文档类型已保存: ${documentType}`);
      }
    }
    
    // console.log(`【DEBUG-HOOK】[重新生成] 开始重新生成，传入文档类型: ${documentType}，使用类型: ${docType}，当前类型: ${currentDocumentType}`);
    
    // 重置状态
    setState((prev) => ({
      ...prev,
      status: "idle",
      error: undefined,
    }));
    
    // 获取GitHub Personal Access Token
    const githubPat = localStorage.getItem("github_pat");
    
    // console.log(`【DEBUG-HOOK】[重新生成] 调用生成函数，类型: ${docType}，github_pat: ${githubPat ? "已设置" : "未设置"}`);
    
    // console.log(`【BUG排查-REGEN-5】调用generateDocument参数: instructions="${instructions.substring(0, 20)}...", github_pat=${!!githubPat}, docType="${docType}"`);
    
    // 显式传递文档类型
    await generateDocument(instructions, githubPat ?? undefined, docType);
  };

  /**
   * 复制文档内容到剪贴板
   * 
   * @returns Promise<void>
   */
  const handleCopy = async () => {
    if (document) {
      await navigator.clipboard.writeText(document);
      alert("Document copied to clipboard!");
    }
  };

  /**
   * 导出文档为Markdown文件
   * 
   * 创建一个下载链接，将文档内容保存为.md文件
   */
  const handleExportDocument = () => {
    if (!document) return;
    
    const blob = new Blob([document], { type: "text/markdown" });
    const url = URL.createObjectURL(blob);
    const a = window.document.createElement("a");
    a.href = url;
    a.download = `${repo}-documentation.md`;
    window.document.body.appendChild(a);
    a.click();
    window.document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  /**
   * 处理API密钥对话框的提交
   * 
   * 保存用户提供的API密钥和选择的模型到本地存储，
   * 然后关闭对话框并重新尝试生成文档
   * 
   * @param apiKey - 用户提供的API密钥
   * @param model - 用户选择的模型 (OpenAI或DeepSeek)
   * @returns Promise<void>
   */
  const handleApiKeySubmit = async (apiKey: string, model: string) => {
    // console.log(`Saving API key and setting model to ${model}`);
    localStorage.setItem("api_key", apiKey);
    localStorage.setItem("selected_model", model);
    
    // 验证是否正确保存到localStorage
    // console.log("Verifying saved model:", localStorage.getItem("selected_model"));
    
    setSelectedModel(model);
    setShowApiKeyDialog(false);
    
    // 如果已经有错误，清除错误并重试
    if (error) {
      setError("");
      setLoading(true);
      const githubPat = localStorage.getItem("github_pat");
      try {
        await generateDocument("", githubPat ?? undefined, currentDocumentType);
      } catch (error) {
        // console.error("Error after setting API key:", error);
        setError(error instanceof Error ? error.message : "An unknown error occurred");
      }
    }
  };

  /**
   * 关闭API密钥对话框
   */
  const handleCloseApiKeyDialog = () => {
    setShowApiKeyDialog(false);
  };

  /**
   * 打开API密钥对话框
   */
  const handleOpenApiKeyDialog = () => {
    setShowApiKeyDialog(true);
  };

  return {
    document,
    error,
    loading,
    lastGenerated,
    cost,
    showApiKeyDialog,
    handleModify,
    handleRegenerate,
    handleCopy,
    handleApiKeySubmit,
    handleCloseApiKeyDialog,
    handleOpenApiKeyDialog,
    handleExportDocument,
    state,
  };
} 